package com.eet.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.eet.excel.controller.listener.OrderListener;
import com.eet.excel.model.OrderModel;
import com.eet.excel.repository.OrderRepository;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 导入控制器
 *
 * @author Administrator
 */
@AllArgsConstructor
@RestController
@RequestMapping("import")
public class ImportController {
    private final OrderRepository orderRepository;

    /**
     * 导入测试
     *
     * @return 是否成功
     */
    @PostMapping("upload")
    public String importExcel(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return "file is none";
        }
        EasyExcel.read(file.getInputStream(), OrderModel.class, new OrderListener(orderRepository)).sheet().doRead();
        return "success";
    }

    /**
     * 导入测试2
     *
     * @return 是否成功
     */
    @PostMapping("build/upload")
    public String importExcelBuild(MultipartFile file) throws IOException {
        ExcelReader excelReader = EasyExcel.read(file.getInputStream(), OrderModel.class, new OrderListener(orderRepository)).build();
        // 读取第一个Sheet页
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();
        return "success";
    }
}
